<template>
  <div class="mask"></div>
  <div class="about" id="containers"></div>
  <!-- <script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=QHQBZ-74AK5-PXIIR-IQBOP-7APDJ-XRBXP"></script> -->
</template>

<script setup>
import { onBeforeMount, toRaw, nextTick, onBeforeUnmount } from 'vue'
import Home from '@/utils/home.js'
import emitter from '@/libs/mini3d/utils/mitt'
import { useRouter } from 'vue-router'

const router = useRouter()

let map = ''
let marker = ''
let time = ''
let markerArr = []

let list = ''
let addMarkerArr = []

let center = toRaw(router).currentRoute.value.query.center
let projectId = toRaw(router).currentRoute.value.query.data

onBeforeMount(async () => {
  // 查全部的，只是把焦点聚焦在某一个城市
  let data = await Home.getMapDevice({
    projectId: projectId,
    province: '',
    city: '',
    area: '',
  })

  list = data.list
  dealData(data.list)
  initMap()
  nextTick(() => {
    intervalGetData(projectId)
  })

  emitter.on('changeProject', async projectId => {
    clearInterval(time)
    projectId = projectId.projectId
    console.log('我拿到的项目id是' + projectId)
    let delIdx = []
    list.forEach(item => {
      delIdx.push(item.id)
    })
    if (delIdx.length) {
      marker.remove(delIdx)
    }
    // 拿到了新的projectId就要发送请求
    let data = await Home.getMapDevice({
      projectId: projectId,
      province: '',
      city: '',
      area: '',
    })
    list = data.list
    // 将旧的设备id全找出来，移除掉，然后把新的设备点加上去，之后再每隔3s调用一下数据请求的接口
    if (list.length > 0) {
      dealData(list, 'add')
      marker.add(addMarkerArr)
      addMarkerArr = []
    }

    nextTick(() => {
      intervalGetData(projectId)
    })
  })
})

onBeforeUnmount(() => {
  clearInterval(time)
})
function initMap() {
  // // 定义地图中心点坐标
  let [x, y] = center
  var centers = new window.TMap.LatLng(y, x)
  // 定义map变量，调用 TMap.Map() 构造函数创建地图
  map = new window.TMap.Map(document.getElementById('containers'), {
    center: centers, // 设置地图中心点坐标
    zoom: 11, // 设置地图缩放级别
    pitch: 43.5, // 设置俯仰角
    rotation: 45, // 设置地图旋转角度
    mapStyleId: 'style1',
    showControl: false, //是否显示控件
  })
  //初始化marker
  marker = new window.TMap.MultiMarker({
    id: 'marker-layer',
    map: map,
    styles: {
      markerError: new window.TMap.MarkerStyle({
        width: 35,
        height: 35,
        anchor: { x: 30, y: 40 },
        src: '',
      }),
      markerOffline: new window.TMap.MarkerStyle({
        width: 35,
        height: 35,
        anchor: { x: 30, y: 40 },
        src: '',
      }),
      markerOnline: new window.TMap.MarkerStyle({
        width: 35,
        height: 35,
        anchor: { x: 30, y: 40 },
        src: '',
      }),
      markerWarn: new window.TMap.MarkerStyle({
        width: 35,
        height: 35,
        anchor: { x: 30, y: 40 },
        src: '',
      }),
    },
    geometries: markerArr,
  })

  let infoWindow = new window.TMap.InfoWindow({
    map: map,
    position: new window.TMap.LatLng(39.984104, 116.307503),
    offset: { x: 110, y: 110 }, //设置信息窗相对position偏移像素
    enableCustom: true,
    content: `<div class="box error">
        <div>
          <div class="device-title">35155246225622145</div>
          <p>设备名称：我是一台设备</p>
          <p>状态：正常</p>
          <p>气体类型：可燃气体</p>
          <p>浓度值：124%LEL</p>
            <div class="location">
              <span class="l-title">位置：<span>
              <span class="more">我是位置我是位置我是位置我是位置我是位置我是位置我是位置我是位置</span>
          </div>
        </div>
        </div>`,
  })

  infoWindow.close() //初始关闭信息窗关闭
  marker.on('click', function (evt) {
    let id = evt.geometry.properties.deviceId

    router.push({
      path: '/device/deviceInfo',
      query: { id },
    })
  })
  marker.on('mouseout', function () {
    infoWindow.close()
  })
  marker.on('mouseover', function (evt) {
    //设置infoWindow
    infoWindow.open() //打开信息窗
    infoWindow.setPosition(evt.geometry.position) //设置信息窗位置
    let info = evt.geometry.properties
    let typeClass = ''
    let status = '正常'
    if (info.warnSatus) {
      if (info.warnLevel == 6) {
        typeClass = 'error'
        status = '故障'
      } else if (info.warnLevel == 9 || info.status == 0) {
        typeClass = 'offline'
        status = '离线'
      } else if (info.warnLevel == 10 || info.warnLevel == 11) {
        typeClass = 'warn'
        if (info.warnLevel == 10) {
          status = '低报'
        } else {
          status = '高报'
        }
      } else {
        typeClass = 'online'
        status = '在线'
      }
    } else {
      if (info.status) {
        typeClass = 'online'
        status = '在线'
      } else {
        typeClass = 'offline'
        status = '离线'
      }
    }

  
    infoWindow.setContent(
      // `<div class="box ${typeClass}">
      //   <div>
      //     <div class="device-title">${info.deviceId}</div>
      //     <div>设备名称：${info.name ? info.name : '- -'}</div>
      //     <div>状态：${status}</div>
      //     <div>气体类型：${info.type == 'oxygen' ? '氧气' : '可燃气'}</div>
      //     <div>浓度值：${info.concentration || '--'}%LEL</div>
      //       <div class="location">
      //         <span class="l-title">位置：<span>
      //         <span class="more">${info.location}</span>
      //     </div>
      //   </div>
      //   </div>`,
      `<div class="box ${typeClass}">
        <div>
          <div class="device-title">${info.deviceId}</div>
            <div style="margin: 4px 0;display: flex;align-items: baseline;">
              <div style="flex-shrink: 0;">设备名称：</div>
              <div style="line-height: 20px;">${info.name ? info.name : '- -'}</div>
            </div>
             <div style="margin: 4px 0;display: flex;align-items: baseline;">
              <div style="flex-shrink: 0;">状态：</div>
              <div style="line-height: 20px;">${status}--${info.status}</div>
            </div>
             <div style="margin: 4px 0;display: flex;align-items: baseline;">
              <div style="flex-shrink: 0;">气体类型：</div>
              <div style="line-height: 20px;">${info.type == 'oxygen' ? '氧气' : '可燃气'}</div>
            </div>
             <div style="margin: 4px 0;display: flex;align-items: baseline;">
              <div style="flex-shrink: 0;">浓度值：</div>
              <div style="line-height: 20px;">${info.concentration}%LEL</div>
            </div>
            <div style="margin: 4px 0;display: flex;align-items: baseline;">
              <div style="flex-shrink: 0;">位置：</div>
              <div style="line-height: 20px;">${info.location || '- -'}</div>
            </div>
        </div>
      </div>`,
    )
  })

  emitter.emit('loadingFinish')
}
function dealData(list, tag) {
  list.forEach(item => {
    let obj = {
      id: '',
      styleId: '',
      position: '',
      properties: {},
    }

    if (item.coord.length > 1) {
      obj.id = item.id
      if (item.warnSatus) {
        if (item.warnLevel == 6) {
          obj.styleId = 'markerError'
        } else if (item.warnLevel == 9) {
          obj.styleId = 'markerOffline'
        } else if (item.warnLevel == 10 || item.warnLevel == 11) {
          obj.styleId = 'markerWarn'
        } else {
          obj.styleId = 'markerOnline'
        }
      } else {
        if (item.status) {
          obj.styleId = 'markerOnline'
        } else {
          obj.styleId = 'markerOffline'
        }
      }
      // 把精度和纬度区分开  coord: "113.651073,34.735409",
      let [x, y] = item.coord.split(',')
      console.log('x和y的值是' + x, y)
      obj.position = new window.TMap.LatLng(y, x)
      obj.properties = {
        name: item.name,
        status: item.status,
        concentration: item.concentration,
        type: item.type,
        location: item.location,
        deviceId: item.deviceId,
        warnSatus: item.warnSatus,
        warnLevel: item.warnLevel,
      }
      if (tag) {
        addMarkerArr.push(obj)
      } else {
        markerArr.push(obj)
      }
    }
  })
}

function intervalGetData(id) {
  time = setInterval(async () => {
    let addList = []
    let deleteList = []
    let data = await Home.getMapDevice({
      projectId: id,
      province: '',
      city: '',
      area: '',
    })
    let dataList = data.list
    // 看是否有新增加的或者减少的，来确认具体的后，加入新的数组里面
    for (let i = 0; i < dataList.length; i++) {
      let tag = 0
      for (let j = 0; j < list.length; j++) {
        if (dataList[i]['id'] == list[j]['id']) {
          tag++
          break
        }
      }
      if (tag == 0) {
        addList.push(dataList[i])
      }
    }

    for (let k = 0; k < list.length; k++) {
      let tag = 0
      for (let w = 0; w < dataList.length; w++) {
        if (dataList[w]['id'] == list[k]['id']) {
          tag++
          break
        }
      }
      if (tag == 0) {
        deleteList.push(list[k]['id'])
      }
    }
    list = dataList
    // 数据有变化，修改marker
    if (deleteList.length > 0) {
      marker.remove(deleteList)
    }

    if (addList.length > 0) {
      dealData(addList, 'add')
      marker.add(addMarkerArr)
      addMarkerArr = []
    }
  }, 3000)
}
</script>
<style>
.mask {
  width: 100%;
  height: 100%;
  position: absolute;
  background: rgba(3, 5, 75, 0.534);
  opacity: 0.5;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.about {
  width: 100%;
  height: 100%;
}
.box {
  color: #d1eaff;
  text-align: left;
  line-height: 18px;
  font-size: 14px;
  width: 300px;
  padding: 20px;
  border-radius: 16px;
  background: rgba(1, 1, 25, 0.9);
  box-sizing: border-box;
  margin-left: 30px;
}

.box div {
  line-height: 20px;
}
.location {
  display: flex;
}
.error {
  box-shadow: inset 0px 0px 30px 10px rgba(254, 211, 106, 0.8);
}
.error .device-title {
  font-size: 14px;
  color: rgb(254, 211, 106);
}
.online {
  box-shadow: inset 0px 0px 20px 10px rgba(111, 227, 186, 0.8);
}
.online .device-title {
  font-size: 14px;
  color: rgb(111, 227, 186);
}
.offline {
  box-shadow: inset 0px 0px 20px 10px rgba(188, 200, 214, 0.8);
}
.offline .device-title {
  font-size: 14px;
  color: rgb(188, 200, 214);
}
.warn {
  box-shadow: inset 0px 0px 20px 10px rgba(255, 118, 126, 0.8);
}
.warn .device-title {
  font-size: 14px;
  color: rgb(255, 118, 126);
}
</style>